package top.igotcha.chapter.chapter7.ForkAndJoin;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author Gotcha
 * @date 2021/3/16
 * @describe
 */
@Slf4j(topic = "ForkAndJoinTest02")
public class ForkAndJoinTest02 {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(4);
        System.out.println(pool.invoke(new MyTask(0,5)));
    }

    static class MyTask extends RecursiveTask<Integer> {
        int begin;
        int end;
        public MyTask(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }
        @Override
        public String toString() {
            return "{" + begin + "," + end + '}';
        }
        @Override
        protected Integer compute() {
            // 5, 5
            if (begin == end) {
                log.debug("join() {}", begin);
                return begin;
            }
            // 4, 5
            if (end - begin == 1) {
                log.debug("join() {} + {} = {}", begin, end, end + begin);
                return end + begin;
            }
            // 1 5
            int mid = (end + begin) / 2; // 3
            MyTask t1 = new MyTask(begin, mid); // 1,3
            t1.fork();
            MyTask t2 = new MyTask(mid + 1, end); // 4,5
            t2.fork();
            log.debug("fork() {} + {} = ?", t1, t2);
            int result = t1.join() + t2.join();
            log.debug("join() {} + {} = {}", t1, t2, result);
            return result;
        }
    }
}
